
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import UserRegistrationForm, UserLoginForm
from .models import User,UserKeyPair
from .models import UserActivityLog,CustomerProfile,ProducerProfile,Order
import logging,os
from .forms import AgriculturalProductForm
from django.db import transaction
from django.http import HttpResponseRedirect
from django.urls import reverse


logger = logging.getLogger(__name__)

def log_user_activity(user, action, description=None, request=None):
    ip_address = None
    user_agent = None
    if request:
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip_address = x_forwarded_for.split(',')[0]
        else:
            ip_address = request.META.get('REMOTE_ADDR')
        user_agent = request.META.get('HTTP_USER_AGENT')

    UserActivityLog.objects.create(
        user=user,
        action=action,
        description=description,
        ip_address=ip_address,
        user_agent=user_agent
    )


def home_view(request):
    return render(request, 'home.html')

def register_view(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            role = form.cleaned_data['role']
            user.save()

            # 根据角色创建对应 Profile
            if role == 'customer':
                CustomerProfile.objects.create(
                    user=user,
                    address=form.cleaned_data.get('address'),
                    company=form.cleaned_data.get('company')
                )
            elif role == 'producer':
                ProducerProfile.objects.create(
                    user=user,
                    business_license=form.cleaned_data.get('business_license'),
                    company_name=form.cleaned_data.get('company')  # 公司名称共用字段
                )

            # 自动生成密钥对
            UserKeyPair.get_or_create_key_pair(user)

            messages.success(request, '注册成功，请登录！')
            return redirect('login')

    else:
        form = UserRegistrationForm()
    return render(request, 'register.html', {'form': form})




def login_view(request):
    if request.method == 'POST':
        form = UserLoginForm(data=request.POST)  # 显式传递data参数
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)

            if user is not None:
                login(request, user)
                log_user_activity(user, 'login', '用户成功登录', request)
                messages.success(request, '登录成功！')
                return redirect('dashboard')
            else:
                messages.error(request, '用户名或密码错误！')
        else:
            print("Form errors:", form.errors)  # 打印详细错误
            messages.error(request, "请修正以下错误：")

    else:
        form = UserLoginForm()

    return render(request, 'login.html', {'form': form})


from django.db.models import Count, Q
from datetime import timedelta
from django.utils import timezone


from django.db.models import Count, Q, Sum
from datetime import timedelta
from django.utils import timezone

@login_required
def dashboard_view(request):
    if request.user.is_admin():
        # 获取所有用户信息
        users = User.objects.all()

        # 用户统计
        total_users = users.count()
        active_users = users.filter(is_active=True).count()
        today_logins = users.filter(last_login__date=timezone.now().date()).count()

        # 加密数据统计
        total_encryptions = EncryptedData.objects.count()
        recent_encryptions = EncryptedData.objects.filter(created_at__gte=timezone.now() - timedelta(days=30)).count()
        total_encryption_records = total_encryptions

        # 获取所有用户的最近活动（前 20 条）
        recent_activities = UserActivityLog.objects.select_related('user').order_by('-created_at')[:20]

        growth_percentage = 0
        last_month_encryptions = EncryptedData.objects.filter(
            created_at__lt=timezone.now() - timedelta(days=30)
        ).count()
        if last_month_encryptions > 0:
            growth_percentage = (recent_encryptions / last_month_encryptions) * 100

        context = {
            'users': users,
            'total_users': total_users,
            'active_users': active_users,
            'today_logins': today_logins,
            'total_encryptions': total_encryptions,
            'recent_encryptions': recent_encryptions,
            'total_encryption_records': total_encryption_records,
            'growth_percentage': growth_percentage,
            'recent_activities': recent_activities,  # ←← 显示所有用户的活动
        }

        return render(request, 'admin_dashboard.html', context)
    else:
        recent_activities = request.user.activity_logs.order_by('-created_at')[:10]
        # 如果是管理员获取所有的商品。
        if request.user.is_admin():
            products = AgriculturalProduct.objects.all()
        else:
            products = AgriculturalProduct.objects.filter(user=request.user)
        products = AgriculturalProduct.objects.filter(user=request.user)
        return render(request, 'user_dashboard.html', {
            'recent_activities': recent_activities,
            'products': products  # ← 添加这一行
        })




def logout_view(request):
    user = request.user
    logout(request)
    if user.is_authenticated:
        log_user_activity(user, 'logout', '用户成功登出', request)
    messages.success(request, '已成功登出！')

    # 清空所有旧消息（⚠️ 慎用）
    storage = messages.get_messages(request)
    storage.used = True  # 清除未消费的消息

    return redirect('home')

#查看用户信息
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404

@login_required
def user_profile_view(request, user_id=None):
    # 如果传入 user_id，则管理员查看指定用户；否则查看自己
    if user_id:
        if not request.user.is_admin():
            messages.error(request, "您没有权限查看其他用户信息。")
            return redirect('dashboard')
        target_user = get_object_or_404(get_user_model(), id=user_id)
    else:
        target_user = request.user

    # 获取加密记录并按时间倒序排列
    encryption_records = EncryptedData.objects.filter(user=target_user).order_by('-created_at')[:5]

    # 获取 ECC 公钥
    try:
        public_key = target_user.key_pair.public_key if hasattr(target_user, 'key_pair') else '未生成密钥'
    except UserKeyPair.DoesNotExist:
        public_key = '未生成密钥'

    return render(request, 'user_profile.html', {
        'user': target_user,
        'encryption_records': encryption_records,
        'public_key': public_key
    })

#编辑
@login_required
def user_edit_view(request):
    user = request.user

    if request.method == 'POST':
        email = request.POST.get('email')
        phone = request.POST.get('phone')

        # 更新字段
        user.email = email
        user.phone = phone
        user.save()

        messages.success(request, '资料更新成功！')
        return redirect('user_profile')

    return render(request, 'user_edit.html', {
        'user': user
    })





# encryption/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import EncryptedData
from .forms import TextEncryptionForm


@login_required
def text_encrypt_view(request):
    """文本加密视图"""
    if request.method == 'POST':
        form = TextEncryptionForm(request.POST)
        if form.is_valid():
            plaintext = form.cleaned_data['plaintext']
            encrypted_data = EncryptedData().encrypt_data(plaintext, request.user)

            if encrypted_data:
                log_user_activity(request.user, 'text_encrypt', f"加密了文本：{plaintext[:20]}...", request)
                messages.success(request, '数据加密成功！')
                return redirect('dashboard')
            else:
                messages.error(request, '加密失败，请重试')
    else:
        form = TextEncryptionForm()
    return render(request, 'text_encrypt.html', {'form': form})


@login_required
def encryption_history_view(request):
    if request.user.is_admin():
        data_list = EncryptedData.objects.all().order_by('-created_at')
        message = '管理员访问了全量加密历史'
    elif request.user.is_customer or request.user.is_producer:
        data_list = EncryptedData.objects.filter(user=request.user).order_by('-created_at')
        message = '用户访问了自己的加密历史'
    else:
        messages.error(request, "您没有权限查看加密记录。")
        return redirect('home')  # 或者返回错误页面

    log_user_activity(request.user, 'view_history', message, request)

    return render(request, 'encryption_history.html', {
        'data_list': data_list
    })



@login_required
def encryption_detail_view(request, pk):
    try:
        if request.user.is_admin():
            encrypted_data = EncryptedData.objects.get(pk=pk)
        else:
            encrypted_data = EncryptedData.objects.get(pk=pk, user=request.user)
    except EncryptedData.DoesNotExist:
        messages.error(request, "未找到对应的加密记录。")
        return redirect('encryption_history')

    try:
        decrypted_data = encrypted_data.decrypt()
    except Exception as e:
        decrypted_data = f"解密失败: {str(e)}"
        messages.error(request, '解密过程中发生错误！')

    log_user_activity(request.user, 'view_detail', f"查看并尝试解密加密记录 ID: {pk}", request)

    return render(request, 'encryption_detail.html', {
        'encrypted_data': encrypted_data,
        'decrypted_data': decrypted_data
    })

@login_required
def input_data(request):
    if request.method == 'POST':
        form = AgriculturalProductForm(request.POST, request.FILES)
        if form.is_valid():
            product = form.save(commit=False)
            product.user = request.user
            product.is_listed = True  # 设置为已上架
            product.save()

            raw_material = product.raw_material_source
            process = product.production_process
            batch = product.inspection_batch
            logistics = product.logistics_flow
            anti_counterfeit = product.anti_counterfeiting_certification

            plaintext = f"""
原材料来源：{raw_material}
生产过程：{process}
检验批次：{batch}
物流流转：{logistics}
防伪鉴证：{anti_counterfeit}
            """.strip()

            encrypted_data = EncryptedData().encrypt_data(plaintext, request.user)
            if encrypted_data:
                encrypted_data.agricultural_product = product
                encrypted_data.user = request.user
                encrypted_data.save()
                log_user_activity(request.user, 'input_data', '上传了商品数据', request)
                messages.success(request, "信息提交并加密成功！")
            else:
                messages.warning(request, "信息已保存，但加密失败。")

            return redirect('input_data')

    else:
        form = AgriculturalProductForm()

    return render(request, 'input_data.html', {'form': form})



from django.shortcuts import render, redirect
from .models import AgriculturalProduct, EncryptedData
from django.contrib.auth.decorators import login_required

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

@login_required
def agricultural_product_list(request):
    query = request.GET.get('q', '')  # 获取查询关键词

    if request.user.is_admin():
        products_queryset = AgriculturalProduct.objects.all().order_by('-id')
    else:
        products_queryset = AgriculturalProduct.objects.filter(user=request.user).order_by('-id')

    # 如果有搜索词，则进行过滤
    if query:
        products_queryset = products_queryset.filter(
            Q(product_name__icontains=query) |
            Q(raw_material_source__icontains=query) |
            Q(production_process__icontains=query) |
            Q(inspection_batch__icontains=query)
        )

    # 分页设置（每页显示10条）
    paginator = Paginator(products_queryset, 10)  # 每页显示10个商品
    page = request.GET.get('page')

    try:
        paginated_products = paginator.page(page)
    except PageNotAnInteger:
        paginated_products = paginator.page(1)
    except EmptyPage:
        paginated_products = paginator.page(paginator.num_pages)

    # 构造带加密状态和图片的数据列表
    product_list = []
    for product in paginated_products:
        is_encrypted = EncryptedData.objects.filter(agricultural_product=product).exists()
        product_list.append({
            'id': product.id,
            'product_name': product.product_name,
            'raw_material_source': product.raw_material_source,
            'production_process': product.production_process,
            'inspection_batch': product.inspection_batch,
            'is_encrypted': is_encrypted,
            'product_image': product.product_image,
            'price': product.price,
            'created_at': product.created_at,
            'is_listed': product.is_listed,
            'is_sold': product.is_sold,
        })

    log_user_activity(request.user, 'agricultural_product_list', '查询农产品商品列表', request)

    return render(request, 'agricultural_product_list.html', {
        'products': product_list,
        'query': query,
        'paginator': paginator,
        'page_obj': paginated_products,
    })








@login_required
def decrypt_agricultural_data(request, product_id):
    try:
        if request.user.is_admin():
            product = AgriculturalProduct.objects.get(id=product_id)
            encrypted_data = EncryptedData.objects.get(agricultural_product=product)
        else:
            product = AgriculturalProduct.objects.get(id=product_id, user=request.user)
            encrypted_data = EncryptedData.objects.get(agricultural_product=product)
            messages.error(request, "您没有权限进行解密操作。")
            return redirect('agricultural_product_list')
    except (AgriculturalProduct.DoesNotExist, EncryptedData.DoesNotExist):
        messages.error(request, "未找到对应的加密数据。")
        return redirect('agricultural_product_list')

    decrypted_text = encrypted_data.decrypt()
    log_user_activity(request.user, 'decrypt', '解密了数据'+decrypted_text, request)

    return render(request, 'decrypted_data_detail.html', {
        'product': product,
        'decrypted_text': decrypted_text
    })

from django.shortcuts import render, redirect
from .models import AgriculturalProduct
from django.contrib.auth.decorators import login_required
from .models import User
from django.core.exceptions import PermissionDenied


@login_required
def product_sell(request):
    """
    展示生产商自己的农产品列表，用于上架销售
    """
    if not request.user.is_producer:
        raise PermissionDenied("您不是生产商，无法访问此页面。")

    # 获取该用户的所有农产品
    products = AgriculturalProduct.objects.filter(user=request.user)
    log_user_activity(request.user, 'product_sell', '获取了用户的所有农产品' , request)

    return render(request, 'product_sell.html', {'products': products})


@login_required
def sell_product(request, product_id):

    try:
        product = AgriculturalProduct.objects.get(id=product_id, user=request.user)
    except AgriculturalProduct.DoesNotExist:
        messages.error(request, "未找到对应商品")
        return redirect('product_sell')


    product.is_listed = True
    product.save()
    log_user_activity(request.user, 'sell_product', '上架了商品', request)

    messages.success(request, "商品已成功上架！")
    return redirect('product_sell')


#买东西
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.db.models import Q


@login_required
def product_catalog(request):
    if not request.user.is_customer:
        messages.error(request, "您不是顾客，无法访问此页面。")
        return redirect('user_dashboard')

    query = request.GET.get('q', '')

    products_list = AgriculturalProduct.objects.filter(is_listed=True, is_sold=False).order_by('-created_at')

    if query:
        products_list = products_list.filter(
            Q(product_name__icontains=query) |
            Q(raw_material_source__icontains=query) |
            Q(production_process__icontains=query)
        )

    paginator = Paginator(products_list, 12)
    page = request.GET.get('page')

    try:
        products = paginator.page(page)
    except PageNotAnInteger:
        products = paginator.page(1)
    except EmptyPage:
        products = paginator.page(paginator.num_pages)

    log_user_activity(request.user, 'product_catalog', '查看了商品', request)

    return render(request, 'product_catalog.html', {'products': products, 'query': query})


# views.py

@login_required
def place_order(request, product_id):
    product = get_object_or_404(AgriculturalProduct, id=product_id, is_listed=True)

    if request.method == 'POST':
        shipping_address = request.POST.get('shipping_address')
        quantity = request.POST.get('quantity')

        try:
            quantity = int(quantity)
            if quantity <= 0:
                raise ValueError("数量必须大于0")
        except (ValueError, TypeError):
            messages.error(request, "请输入有效的购买数量。")
            return redirect('product_catalog')  # 返回商品目录页

        # 创建订单
        order = Order.objects.create(
            user=request.user,
            product=product,
            shipping_address=shipping_address,
            quantity=quantity
        )

        # 更新商品状态为已售出，并下架
        product.is_sold = True
        product.is_listed = False
        product.sold_at = timezone.now()
        product.save()

        messages.success(request, "订单提交成功！请前往我的订单查看")
        return redirect('order_history')
    log_user_activity(request.user, 'place_order', '下单了商品', request)

    return redirect('product_catalog')


from django.db.models import Q

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


@login_required
def order_history_view(request):
    if not request.user.is_customer:
        messages.error(request, "您不是顾客，无法访问此页面。")
        return redirect('user_dashboard')

    query = request.GET.get('q', '')  # 获取查询关键词

    # 查询当前用户的订单，并根据关键词过滤
    orders_queryset = Order.objects.filter(user=request.user).select_related('product')

    if query:
        orders = orders_queryset.filter(
            Q(product__product_name__icontains=query) |
            Q(shipping_address__icontains=query)
        )
    else:
        orders = orders_queryset

    # 添加分页功能
    paginator = Paginator(orders, 10)  # 每页显示10个订单
    page = request.GET.get('page')

    try:
        paginated_orders = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，默认显示第一页
        paginated_orders = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，显示最后一页
        paginated_orders = paginator.page(paginator.num_pages)

    log_user_activity(request.user, 'order_history_view', '查看了历史订单', request)

    return render(request, 'order_history.html', {
        'orders': paginated_orders,
        'query': query,
        'paginator': paginator,
        'page_obj': paginated_orders,
    })


@login_required
def cancel_order(request, order_id):
    # 获取订单
    order = get_object_or_404(Order, id=order_id, user=request.user)

    # 只有待支付状态的订单可以取消
    if order.status == 'pending':
        with transaction.atomic():
            # 更新订单状态为已取消
            order.status = 'cancelled'
            order.save()

            # 将对应的商品重新上架（如果需要）
            product = order.product
            product.is_listed = True
            product.is_sold = False
            product.save()

    messages.success(request, "订单已成功取消！")
    log_user_activity(request.user, 'cancel_order', '取消了订单', request)
    return redirect('order_history')




@login_required
def toggle_product_listing(request, product_id):
    product = get_object_or_404(AgriculturalProduct, id=product_id)

    # 管理员可以操作所有商品，普通用户只能操作自己发布的商品
    if not request.user.is_admin and (not request.user.is_producer or product.user != request.user):
        raise PermissionDenied("您没有权限进行此操作")

    # 切换上架状态
    action = request.GET.get('action', 'list')

    if action == 'unlist':
        product.is_listed = False
        messages.success(request, "商品已成功下架")
    else:
        product.is_listed = True
        messages.success(request, "商品已成功上架")

    product.save()
    log_user_activity(request.user, 'toggle_product_listing', f'切换了商品上架状态为{action}', request)

    return HttpResponseRedirect(reverse('agricultural_product_list'))

@login_required
def edit_agricultural_product(request, product_id):
    product = get_object_or_404(AgriculturalProduct, id=product_id)

    if not request.user.is_admin and product.user != request.user:
        messages.error(request, "您没有权限编辑此商品")
        return redirect('agricultural_product_list')

    if request.method == 'POST':
        form = AgriculturalProductForm(request.POST, request.FILES, instance=product)
        if form.is_valid():
            # 打印调试信息
            if 'product_image' in request.FILES:
                old_image = product.product_image
                print("📄 接收到新图片:", request.FILES['product_image'].name)
                if old_image and os.path.isfile(old_image.path):
                    print("🗑️ 删除旧文件:", old_image.path)
                    os.remove(old_image.path)
            form.save()
            print("📷 当前图片字段值:", product.product_image.name)
            messages.success(request, "商品信息已成功更新！")
            return redirect('agricultural_product_list')
        else:
            print("🚫 表单验证失败:", form.errors)
    else:
        form = AgriculturalProductForm(instance=product)
    log_user_activity(request.user, 'edit_agricultural_product', '编辑了商品', request)
    return render(request, 'edit_agricultural_product.html', {
        'form': form,
        'product': product
    })


from django.db.models import Q


from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q

def sold_orders_all(request):
    query = request.GET.get('q', '')  # 获取查询关键词

    # 权限控制：管理员查看所有订单，生产商只能看自己的商品相关订单
    if request.user.is_admin():
        orders_queryset = Order.objects.filter(status='pending')
    elif request.user.is_producer:
        orders_queryset = Order.objects.filter(
            product__user=request.user,
            status='pending'
        )
    else:
        # 非管理员、非生产商用户无权访问
        messages.error(request, "您没有权限查看此页面。")
        return redirect('home')  # 或者重定向到合适的页面

    # 如果有搜索词，则进行过滤（仅限当前用户/管理员可见范围）
    if query:
        orders_queryset = orders_queryset.filter(
            Q(product__product_name__icontains=query) |
            Q(user__username__icontains=query)
        )

    log_user_activity(request.user, 'sold_orders_all', '查看了所有订单', request)

    # 添加分页功能
    paginator = Paginator(orders_queryset, 10)  # 每页显示10个订单
    page = request.GET.get('page')

    try:
        paginated_orders = paginator.page(page)
    except PageNotAnInteger:
        paginated_orders = paginator.page(1)
    except EmptyPage:
        paginated_orders = paginator.page(paginator.num_pages)

    return render(request, 'all_sold_orders.html', {
        'orders': paginated_orders,
        'query': query,
        'paginator': paginator,
        'page_obj': paginated_orders,
    })



def order_details(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    log_user_activity(request.user, 'order_details', '查看了订单详情', request)
    return render(request, 'order_details.html', {'order': order})

@login_required
def delete_agricultural_product(request, product_id):
    product = get_object_or_404(AgriculturalProduct, id=product_id)

    # 权限控制：仅管理员或本人可删除
    if not request.user.is_admin and product.user != request.user:
        messages.error(request, "您没有权限删除该商品。")
        return redirect('agricultural_product_list')

    product.delete()
    log_user_activity(request.user, 'delete_agricultural_product', f'删除了商品 ID:{product_id}', request)
    messages.success(request, "商品已成功删除。")

    return redirect('agricultural_product_list')


from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import User
from .forms import UserEditForm  # 我们接下来会创建这个表单
@login_required
def user_edit(request, user_id):
    target_user = get_object_or_404(User, id=user_id)

    # 权限控制：非管理员不能编辑他人资料
    if not request.user.is_admin() and request.user.id != target_user.id:
        messages.error(request, "您没有权限编辑此用户信息。")
        return redirect('dashboard')

    if request.method == 'POST':
        form = UserEditForm(request.POST, instance=target_user)
        if form.is_valid():
            form.save()
            messages.success(request, "用户信息已更新。")
            return redirect('dashboard')  # 或者跳转到用户详情页
    else:
        form = UserEditForm(instance=target_user)

    return render(request, 'user_edit.html', {
        'form': form,
        'target_user': target_user
    })




